package com.emar.adx.yiqifa.util;

import java.sql.*;

/**
 * Created by Administrator on 2015/11/18.
 */
public class JdbcUtil {

    static {
        try {
            //加载驱动
            Class.forName(ConfigurationFactory.getConfiguration("jdbc.properties").getString("jdbc.driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection conn = null;
        String url = ConfigurationFactory.getConfiguration("jdbc.properties").getString("jdbc.url");//获取URL
        String user = ConfigurationFactory.getConfiguration("jdbc.properties").getString("jdbc.username");//获取登录名
        String pwd = ConfigurationFactory.getConfiguration("jdbc.properties").getString("jdbc.password");//获取登录密码
        try {
            //连接数据库
            conn = DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //释放资源
    public static void release(Object o){
        if (o == null){
            return;
        }
        if (o instanceof ResultSet){
            try {
                ((ResultSet)o).close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if(o instanceof Statement){
            try {
                ((Statement)o).close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (o instanceof Connection){
            Connection c = (Connection)o;
            try {
                if (!c.isClosed()){
                    c.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public static void release(ResultSet rs, Statement stmt,
                               Connection conn){
        release(rs);
        release(stmt);
        release(conn);
    }
}
